//
//  UserViewModel.swift
//  xiaoqiao
//
//  Created by 冷子豪 on 2017/8/12.
//  Copyright © 2017年 冷子豪. All rights reserved.
//

import Foundation

let userViewModel = UserViewModel()

class UserViewModel {
    
    /// checklogin() -> 检查账户密码是否正确
    ///
    /// - Parameters:
    ///   - username: 待检查 用户名
    ///   - password: 待检查 密码
    /// - Returns:  0 -> 登陆失败
    ///             1 -> 登录成功
    func checklogin(username:String,password:String) -> String{
        //
        var flag = "0"
        
        // 同步Post
        // 1、创建URL对象；
        let url:URL! = URL(string:"\(info.API_URL)/xqjr/user/appUserLogin?phone=\(username)&password=\(password)");
        print("\(info.API_URL)/xqjr/user/appUserLogin?phone=\(username)&password=\(password)")
        // 2、创建Request对象
        // url: 请求路径
        // cachePolicy: 缓存协议
        // timeoutInterval: 网络请求超时时间(单位：秒)
        let urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
        // 3、响应对象
        var response:URLResponse?
        
        // 4、发出请求
        do {
            // MARK: - 接受后台数据
            let received =  try NSURLConnection.sendSynchronousRequest(urlRequest, returning: &response)
            flag = NSString(data:received,encoding:String.Encoding.utf8.rawValue)! as String
        } catch let error{
            print(error.localizedDescription);
        }
        return flag
    }
    
    /// 登录成功时，获取账号信息
    ///
    /// - Parameter phone: 当前登录手机号
    /// - Returns: 当前用户的user信息
    func getUserByPhone(phone:String) -> User{
        var newUser = User()
        // 同步Get方式
        
        // 1.创建URL对象
        let url:URL! = URL(string:"\(info.API_URL)/xqjr/user/appGetUserByPhone?phone=\(phone)")
        
        // 2.创建Request对象
        // url: 请求路径
        // cachePolicy: 缓存协议
        // timeoutInterval: 网络请求超时时间(单位：秒)
        let urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
        
        // 3.响应对象
        var response:URLResponse?
        
        // 4.发出请求
        do {
            // Data,json数据
            let received =  try NSURLConnection.sendSynchronousRequest(urlRequest, returning: &response)
            // 字典数据
            let dic = try JSONSerialization.jsonObject(with: received, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:Any]
            
            newUser = User(dic: dic)
            
        } catch let error{
            print(error.localizedDescription);
        }
        return newUser
    }
    
    /// 更新用户
    ///
    /// - Parameter data: Json格式的 user 对象
    /// - Returns: <#return value description#>
    func updateUser(data:Data) -> Int{
        var returnNum = 1
        // 同步Post方式
        
        // 1.创建URL对象
        let url:URL! = URL(string:"\(info.API_URL)/xqjr/user/appUserUpdateByUserId")
        
        // 2.创建Request对象
        var urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
        
        // 3、设置请求方式为POST，默认是GET
        urlRequest.httpMethod = "POST"
        
        // 4、设置参数
        urlRequest.httpBody = data;
        
        // 5.响应对象
        var response:URLResponse?
        
        // 6.发出请求
        do {
            let received =  try NSURLConnection.sendSynchronousRequest(urlRequest, returning: &response)
            returnNum = try JSONSerialization.jsonObject(with: received, options: JSONSerialization.ReadingOptions.allowFragments) as! Int
        } catch let error{
            print(error.localizedDescription);
        }
        return returnNum
    }
    
    func getUserByUserId(userid:Int) -> User{
        let newUser = User()
        //
        //        // 同步Get方式
        //        // 1.创建URL对象
        //        let url:URL! = URL(string:"\(info.dataBaseUrl)/xqjr/ascription/getUpGradeByUserId?userid=\(userid)")
        //
        //        // 2.创建Request对象
        //        let urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
        //
        //        // 3.响应对象
        //        var response:URLResponse?
        //
        //        // 4.发出请求
        //        do {
        //            // Data,json数据
        //            let received =  try NSURLConnection.sendSynchronousRequest(urlRequest, returning: &response)
        //            // 返回id
        //            let dic = NSString(data:received,encoding:String.Encoding.utf8.rawValue)! as String
        //            upId = Int(dic)!
        //            //            let dic = try JSONSerialization.jsonObject(with: received, options: JSONSerialization.ReadingOptions.allowFragments)
        //            
        //        } catch let error{
        //            print(error.localizedDescription)
        //        }
        
        return newUser
    }
}
